// Get the cookies
function getCookies(host, path, sort)
{
    var cookies = new Array();

    // If the host is set
    if(host)
    {
        var cookie            = null;
        var cookieEnumeration = Components.classes["@mozilla.org/cookiemanager;1"].getService(Components.interfaces.nsICookieManager).enumerator;
        var cookieHost        = null;
        var cookiePath        = null;

        // Loop through the cookies
        while(cookieEnumeration.hasMoreElements())
        {
            cookie = cookieEnumeration.getNext().QueryInterface(Components.interfaces.nsICookie);

            cookieHost = cookie.host;
            cookiePath = cookie.path;

            // If there is a host and path for this cookie
            if(cookieHost && cookiePath)
            {
                // If the cookie host starts with '.'
                if(cookieHost.charAt(0) == ".")
                {
                    cookieHost = cookieHost.substring(1);
                }

                // If the host and cookie host and path and cookie path match
                if((host == cookieHost || host.indexOf("." + cookieHost) != -1) && (path == cookiePath || path.indexOf(cookiePath) == 0))
                {
                    cookies.push(cookie);
                }
            }
        }

        // If sorting cookies
        if(sort)
        {
            cookies.sort(sortCookies);
        }
    }

    return cookies;
}

// Sorts two cookies
function sortCookies(cookieOne, cookieTwo)
{
    // If cookie one and cookie two are set
    if(cookieOne && cookieTwo)
    {
        var cookieOneHost = cookieOne.host;
        var cookieOneName = cookieOne.name;
        var cookieTwoHost = cookieTwo.host;
        var cookieTwoName = cookieTwo.name;

        // If the cookies are equal
        if(cookieOneHost == cookieTwoHost && cookieOneName == cookieTwoName)
        {
            return 0;
        }
        else if(cookieOneHost < cookieTwoHost || (cookieOneHost == cookieTwoHost && cookieOneName < cookieTwoName))
        {
            return -1;
        }
    }

    return 1;
}